<template>
  <div class="drawOuter fadeInRight">
    <div class="drawinner">
      <header>
        <span>标绘</span>
        <img class="close" src="/images/button/close.png" alt @click="close()" />
      </header>

      <div class="drawtree">
        <el-tree
          ref="tree"
          :props="props"
          :data="treeData"
          show-checkbox
          node-key="id"
          @check-change="handleCheckChange"
          :default-expand-all="true"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span @contextmenu="showMenu($event,node)" class="title" @dblclick="lookTarget(node)">
              <span
                class="icon"
                v-if="data.type"
                :class="{
                                'point':data.type=='Marker',
                                'word':data.type=='Text',
                                'line':data.type=='GroundPolyline',
                                'circle':data.type=='GroundCircle',
                                'rectangle':data.type=='GroundRectangle',
                                'oval':data.type=='GroundEllipse',
                                'surface':data.type=='GroundPolygon',
                                }"
              ></span>
              {{ node.label}}
            </span>
            <!-- <el-input @dblclick="showInput"></el-input> -->
          </span>
        </el-tree>
        <input type="text" v-show="changeLable" @keyup.enter="changNode($event)" ref="input" />
        <contextmenu
          :menu="menu"
          :pos="pos"
          v-if="menushow"
          @rename="rename"
          @delLayers="delLayers"
          @empty="empty"
          @setActLay="setActLay"
          @newLayer="newLayer"
          @editLayer="editLayer"
        ></contextmenu>
      </div>
      <div class="drawtools">
        <markPage ref="markPage" @addLeafNode="addLeafNode" @getLayerId="getLayerId"></markPage>
      </div>
      <Dialog v-show="savePanel">
        <div class="saved">
          <div class="inner">
            <p>是否保存当前方案？</p>
            <div class="buttenrow">
              <el-button class="file" @click="endSavePlan">保存</el-button>
              <el-button
                class="file con"
                @click="()=>{this[saveThen]();this.savePanel=false}"
              >不保存，继续</el-button>
              <el-button class="file" @click="cancel">取消</el-button>
            </div>
          </div>
        </div>
      </Dialog>
      <Dialog v-show="saveNameShow">
        <div class="saved">
          <div class="inner">
            <el-row>
              <label>
                方案名称
                <input type="text" v-model="saveName" @keydown.enter="startSaveName" />
              </label>
            </el-row>
            <div class="buttenrow">
              <el-button class="file" @click="startSaveName">确定</el-button>
              <el-button class="file" @click="cancel">取消</el-button>
            </div>
          </div>
        </div>
      </Dialog>
      <Dialog v-show="radioShow" class="choose">
        <div class="title">选择方案</div>
        <el-select v-model="radio" placeholder="请选择">
          <el-option v-for="(item,i) in planList" :key="i" :label="item.name" :value="i"></el-option>
        </el-select>
        <el-button @click="makeSure(planList[radio])">确定</el-button>
        <el-button @click="closeRadio">取消</el-button>
      </Dialog>
    </div>
  </div>
</template>

<script>
// Marker 点
// Text   文字
// GroundPolyline  线
// GroundCircle   圆
// GroundRectangle 矩形
// GroundEllipse   椭圆
// GroundPolygon   面
import contextmenu from "./contextmenu";
import DrawHelper from "@/DrawHelper/DrawHelper.js";
import layerGroupHandle from "@/DrawHelper/layerGroupHandle.js";
import markPage from "./markPage";
import Dialog from "./Dialog";
export default {
  name: "Draw",
  created() {
    console.log(GV);
  },
  data() {
    return {
      props: {
        label: "label",
        children: "children",
      },
      treeData: [
        {
          id: Cesium.createGuid(),
          label: "方案",
          children: [
            {
              id: Cesium.createGuid(),
              label: "图层",
              children: [],
            },
          ],
        },
      ],
      dataId: null,
      changeLable: false,
      menushow: false,
      menu: null,
      pos: {},
      curNode: null,
      curHTML: null,
      planList: null,
      radioShow: false,
      savePanel: false,
      saveThen: null,
      saveNameShow: false,
      saveName: null,
      radio: 0,
    };
  },
  methods: {
    handleCheckChange(data, flag) {
      if (data.isLeaf) {
        layerGroupHandle.showGeometry(data.id, flag);
      }
    },
    lookTarget(node) {
      if (node.isLeaf) {
        layerGroupHandle.lookGeometry(node.data.id);
      }
    },
    showMenu(e, node) {
      switch (e.button) {
        case 2:
          this.pos.left = e.x + document.body.scrollLeft + "px";
          this.pos.top = e.y + document.body.scrollTop + "px";
          this.curNode = node;
          this.curHTML = e.target;
          let renameObj = {
            name: "重命名",
            fun: "rename",
          };
          let delLayersObj = {
            name: "删除",
            fun: "delLayers",
          };
          let emptyObj = {
            name: "清空",
            fun: "empty",
          };
          let setActLayObj = {
            name: "设为活动图层",
            fun: "setActLay",
          };
          let newLayerObj = {
            name: "新建图层",
            fun: "newLayer",
          };
          let editLayerObj = {
            name: "编辑",
            fun: "editLayer",
          };
          switch (node.level) {
            case 1:
              this.menu = [emptyObj, newLayerObj, renameObj];
              break;
            case 2:
              this.menu = [emptyObj, renameObj, delLayersObj, setActLayObj];
              break;
            case 3:
              this.menu = [renameObj, delLayersObj, editLayerObj];
              break;
          }
          this.menushow = true;
          document.addEventListener("click", this.closeMune, true);
          break;
      }
    },
    changNode(e) {
      this.curNode.data.label = this.$refs.input.value;
      this.$refs.input.value = "";
      this.changeLable = false;
      this.curHTML.removeChild(this.$refs.input);
      document.removeEventListener("click", this.closeRename, false);
    },
    rename() {
      this.menushow = false;
      document.removeEventListener("click", this.closeMune, true);
      this.curHTML.appendChild(this.$refs.input);
      this.changeLable = true;
      this.$refs.input.autofocus = true;
      document.addEventListener("click", this.closeRename, true);
    },
    closeRename(e) {
      if (e.target != this.$refs.input && e.target.className != "menuCon") {
        this.changeLable = false;
        this.curHTML.removeChild(this.$refs.input);
        document.removeEventListener("click", this.closeRename, false);
      }
    },
    delLayers() {
      this.menushow = false;
      document.removeEventListener("click", this.closeMune, true);
      const parent = this.curNode.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === this.curNode.data.id);
      children.splice(index, 1);
      this.curNode.level === 2 &&
        layerGroupHandle.deleteLayer(parent.data.id, this.curNode.data.id);
      this.curNode.level === 3 &&
        layerGroupHandle.removeGeometry(
          this.curNode.data.id,
          parent.parent.data.id,
          parent.data.id
        );
      this.curNode.level === 2 &&
        this.curNode.data.id === this.activeLayer &&
        (this.activeLayer = void 0);
    },
    empty() {
      this.menushow = false;
      document.removeEventListener("click", this.closeMune, true);
      this.curNode.data.children = [];
      new DrawHelper(viewer.scene).stopDrawing();
      this.curNode.level === 1 &&
        layerGroupHandle.clearLayerGroup(this.curNode.data.id),
        (this.activeLayer = void 0);
      this.curNode.level === 2 &&
        layerGroupHandle.clearLayer(
          this.curNode.parent.data.id,
          this.curNode.data.id
        );
    },
    setActLay() {
      this.activeLayer = this.curNode.data.id;
      this.activeLayerParent = this.curNode.parent.data.id;
      layerGroupHandle.setActiveLayer(this.activeLayerParent, this.activeLayer);
      this.menushow = false;
      document.removeEventListener("click", this.closeMune, true);
    },
    newLayer() {
      this.menushow = false;
      document.removeEventListener("click", this.closeMune, true);
      const newChild = {
        id: Cesium.createGuid(),
        label: "默认图层",
        children: [],
      };
      this.curNode.data.children.push(newChild);
      layerGroupHandle.addLayer(
        this.curNode.data.id,
        newChild.id,
        newChild.label
      );
    },
    editLayer() {
      layerGroupHandle.getGeometry(this.curNode.data.id).setEditMode(true);
      this.menushow = false;
    },
    closeMune(e) {
      if (e.target.className != "menuCon") {
        this.menushow = false;
        document.removeEventListener("click", this.closeMune, true);
      }
    },

    async openPlanList() {
      this.$get("wuhao/plan/all").then((res) => {
        this.planList = res;
        this.radioShow = true;
      });
      // getAllPlan().then(res => {
      //     this.planList = res.data
      //     this.radioShow = true
      // })
    },
    async makeSure(planCon) {
      await this.$get("wuhao/plan/one", {
        id: planCon.id,
      }).then((res) => {
        let _self = this;
        let arr = res.content.split("|");
        this.treeData = JSON.parse(arr[0]);
        this.initLayers();
        setTimeout(function () {
          _self.$refs.tree.setChecked(_self.treeData[0].id, true, true);
        }, 0);
        let programme = JSON.parse(arr[1]);
        layerGroupHandle.openProgramme(programme, viewer.scene, {
          startEditCallback: this.$refs.markPage.startEditCallback,
          endEditCallback: this.$refs.markPage.endEditCallback,
        });
        // _self.$parent.$refs.imageManage.leftCompareRight = true
        if (window.rightViewer) {
          setTimeout(function () {
            let geometryArr = layerGroupHandle.getAllGeometry();
            for (let i in geometryArr) {
              if (i === "size") {
                continue;
              }
              if (geometryArr[i].properties.isRight) {
                let options = _self.getOptions(geometryArr[i]);
                let node = _self.$refs.tree.getNode(i);
                layerGroupHandle.removeGeometry(
                  node.data.id,
                  node.parent.parent.data.id,
                  node.parent.data.id
                );
                let geometry = _self.createPrimitive(options);
                geometryArr[i] = geometry;
                geometry._createPrimitive = true;
                let callbacks = _self.$refs.markPage.createCallbacks();
                geometry.startEditCallback = callbacks.startEditCallback;
                geometry.endEditCallback = callbacks.endEditCallback;
                geometry._primitives = rightViewer.scene.primitives;
                rightViewer.scene.primitives.add(geometry);
              }
            }
          }, 0);
        } else {
          setTimeout(function () {
            let geometryArr = layerGroupHandle.getAllGeometry();
            for (let i in geometryArr) {
              if (i === "size") {
                continue;
              }
              if (geometryArr[i].properties.isRight) {
                _self.curNode = _self.$refs.tree.getNode(i);
                _self.delLayers();
              }
            }
          }, 0);
        }

        this.dataId = res.id;
      });
      this.cancel();
    },
    getOptions(primitive) {
      let result = {};
      switch (primitive.getType()) {
        case "Marker":
          result.id = primitive.id;
          result.type = "Marker";
          result.position = GV.Cartesian3.pack(
            primitive._billboards[0].position,
            []
          );
          result.image = primitive._billboards[0].image;
          result.color = primitive._billboards[0].color;
          result.scale = primitive._billboards[0].scale;
          result.properties = primitive._billboards[0].properties;
          break;
        case "Text":
          result.id = primitive.id;
          result.type = "Text";
          result.position = GV.Cartesian3.pack(
            primitive._labels[0].position,
            []
          );
          result.text = primitive._labels[0].text;
          result.font = primitive._labels[0].font;
          result.fillColor = primitive._labels[0].fillColor;
          result.outlineColor = primitive._labels[0].outlineColor;
          result.outlineWidth = primitive._labels[0].outlineWidth;
          result.properties = primitive._labels[0].properties;
          break;
        case "GroundPolyline":
          result.id = primitive.id;
          result.type = "GroundPolyline";
          result.positions = GV.Cartesian3.packArray(primitive.positions, []);
          result.width = primitive.width;
          result.lineType = primitive.lineType;
          result.color = primitive.color;
          result.outlineWidth = primitive.outlineWidth;
          result.outlineColor = primitive.outlineColor;
          result.glowPower = primitive.glowPower;
          result.taperPower = primitive.taperPower;
          result.dashedScale = primitive.dashedScale;
          result.dashedLength = primitive.dashedLength;
          result.properties = primitive.properties;
          break;
        case "GroundPolygon":
          result.id = primitive.id;
          result.type = "GroundPolygon";
          result.positions = GV.Cartesian3.packArray(primitive.positions, []);
          result.color = primitive.color;
          result.outlineColor = primitive.outlineColor;
          result.properties = primitive.properties;
          break;
        case "GroundEllipse":
          result.id = primitive.id;
          result.type = "GroundEllipse";
          result.center = GV.Cartesian3.pack(primitive.getCenter(), []);
          result.rotation = primitive.getRotation();
          result.color = primitive.color;
          result.semiMajorAxis = primitive.semiMajorAxis;
          result.semiMinorAxis = primitive.semiMinorAxis;
          result.properties = primitive.properties;
          break;
        case "GroundCircle":
          result.id = primitive.id;
          result.type = "GroundCircle";
          result.color = primitive.color;
          result.center = GV.Cartesian3.pack(primitive.getCenter(), []);
          result.radius = primitive.getRadius();
          result.properties = primitive.properties;
          break;
        case "GroundRectangle":
          result.id = primitive.id;
          result.type = "GroundRectangle";
          result.color = primitive.color;
          result.extent = primitive.getExtent();
          result.properties = primitive.properties;
          break;
      }
      return result;
    },
    createPrimitive(options) {
      let primitive = null;
      options.scene = rightViewer.scene;
      switch (options.type) {
        case "Marker":
          options.position = GV.Cartesian3.unpack(options.position);
          options.heightReference = GV.HeightReference.CLAMP_TO_GROUND;
          primitive = new GV.Marker(options);
          break;
        case "Text":
          options.position = GV.Cartesian3.unpack(options.position);
          options.heightReference = GV.HeightReference.CLAMP_TO_GROUND;
          primitive = new GV.TextAnnotation(options);
          break;
        case "GroundPolyline":
          options.positions = GV.Cartesian3.unpackArray(options.positions);
          primitive = new GV.GroundPolyline(options);
          break;
        case "GroundPolygon":
          options.positions = GV.Cartesian3.unpackArray(options.positions);
          primitive = new GV.GroundPolygon(options);
          break;
        case "GroundEllipse":
          options.center = GV.Cartesian3.unpack(options.center);
          primitive = new GV.GroundEllipse(options);
          break;
        case "GroundCircle":
          options.center = GV.Cartesian3.unpack(options.center);
          primitive = new GV.GroundCircle(options);
          break;
        case "GroundRectangle":
          primitive = new GV.GroundRectangle(options);
          break;
      }
      return primitive;
    },
    newPlan() {
      this.treeData = [
        {
          id: Cesium.createGuid(),
          label: "默认方案",
          children: [
            {
              id: Cesium.createGuid(),
              label: "默认图层",
              children: [],
            },
          ],
        },
      ];
      this.$refs.tree.setChecked(1, true, true);
      this.initLayers();
      this.cancel();
    },
    initLayers() {
      layerGroupHandle.deleteLayerGroup(this.activeLayerParent);
      this.activeLayerParent = this.treeData[0].id;
      this.activeLayer = this.treeData[0].children[0].id;
      layerGroupHandle.addLayerGroup(this.activeLayerParent, "默认方案");
      layerGroupHandle.addLayer(
        this.activeLayerParent,
        this.activeLayer,
        "默认图层"
      );
      layerGroupHandle.setActiveLayer(this.activeLayerParent, this.activeLayer);
    },
    startSavePlan(callback) {
      this.savePanel = true;
      if (callback) {
        this.saveThen = callback;
      }
    },
    async endSavePlan() {
      this.savePanel = false;
      this.saveName = this.treeData[0].label;
      this.saveNameShow = true;
    },
    async startSaveName() {
      if (this.dataId) {
        let res = await this.$get("/wuhao/plan/ext", {
          name: this.saveName,
          id: this.dataId,
        });
        if (res) {
          this.$message({
            showClose: true,
            message: "命名重复，请更改标绘方案名称",
            type: "warning",
            offset: 500,
          });
        } else {
          this.treeData[0].label = this.saveName;
          this.addNewPlan();
        }
      } else {
        let res = await this.$get("/wuhao/plan/ext", {
          name: this.saveName,
        });
        if (res) {
          this.$message({
            showClose: true,
            message: "命名重复，请更改标绘方案名称",
            type: "warning",
            offset: 500,
          });
        } else {
          this.treeData[0].label = this.saveName;
          this.addNewPlan();
        }
      }
    },
    async addNewPlan() {
      let geoObj = layerGroupHandle.saveProgramme(this.activeLayerParent);
      let obj = {
        name: this.saveName,
        content: JSON.stringify(this.treeData) + "|" + JSON.stringify(geoObj),
      };
      if (this.dataId) {
        obj.id = this.dataId;
      }
      this.$post("wuhao/plan/upd", obj)
        .then((res) => {
          if (res) {
            this.$message({
              showClose: true,
              message: "保存方案成功",
              type: "success",
              offset: 500,
            });
            this.saveNameShow = false;
            if (this.saveThen) {
              this[this.saveThen]();
            }
          }
        })
        .catch((err) => {
          this.$message({
            showClose: true,
            message: `err`,
            type: "warning",
            offset: 500,
          });
        });
    },
    closeRadio() {
      this.radioShow = false;
    },
    addLeafNode(data, primitive, flag = true) {
      data.type = primitive.getType();
      this.$refs.tree.append(data, this.activeLayer);
      this.$refs.tree.setChecked(data.id, flag);
      layerGroupHandle.addGeometry(
        primitive,
        this.activeLayerParent,
        this.activeLayer
      );
    },
    getLayerId() {
      return {
        id: this.activeLayer,
        pId: this.activeLayerParent,
      };
    },
    cancel() {
      this.radioShow = false;
      this.savePanel = false;
      this.saveThen = null;
      this.saveNameShow = false;
    },
    close() {
      this.$store.state.drawIsShow = false;
    },
  },

  mounted() {
    document.addEventListener("click", this.closeMune, true);
    this.activeLayerParent = this.treeData[0].id;
    this.activeLayer = this.treeData[0].children[0].id;
    layerGroupHandle.addLayerGroup(this.activeLayerParent, "默认方案");
    layerGroupHandle.addLayer(
      this.activeLayerParent,
      this.activeLayer,
      "默认图层"
    );
    layerGroupHandle.setActiveLayer(this.activeLayerParent, this.activeLayer);
  },
  components: {
    contextmenu,
    markPage,
    Dialog,
  },
};
</script>

<style lang="scss">
.drawOuter {
  height: 700px;
  overflow: hidden;
  animation-duration: 0.5s;
  position: absolute;
  right: 45px;
  border: 1px solid #00acc4;
  top: 2px;
  z-index: 9;
  background-color: #fff;
  border-radius: 2px;
  color: black;
  font-weight: 400;
  .drawinner {
    background-image: url("/images/left-bg.png");
    background-size: 100% 100%;
    width: 329px;
    height: 100%;
    box-sizing: border-box;
    float: right;
    header {
      width: 100%;
      background-color: #00acc4;
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 35px;
      span {
        font-size: 16px;
        font-weight: 500;
        margin-left: 20px;
      }
      .close {
        cursor: pointer;
        padding: 5px 7px;
      }
    }

    .drawtree {
      height: 40%;
      overflow: hidden;
      overflow-y: auto;
      padding-top: 20px;
      background: white;
      .el-tree {
        background-color: #e7f4fe;
        .el-tree-node__content:hover {
          background-color: #00abc5;
          color: white;
        }
        .title {
          padding-right: 250px;
        }

        .icon {
          width: 18px;
          height: 18px;
          background-size: 100% 100%;
          display: inline-block;
          vertical-align: middle;
          margin-right: 10px;
        }

        .point {
          background-image: url("/images/draw/point.png");
        }

        .line {
          background-image: url("/images/draw/line.png");
        }

        .surface {
          background-image: url("/images/draw/surface.png");
        }

        .oval {
          background-image: url("/images/draw/oval.png");
        }

        .rectangle {
          background-image: url("/images/draw/rectangle.png");
        }

        .word {
          background-image: url("/images/draw/word.png");
        }

        .circle {
          background-image: url("/images/draw/circle.png");
        }
      }
    }
    .drawtree::-webkit-scrollbar {
      width: 4px;
    }
    .drawtree::-webkit-scrollbar-thumb {
      border-radius: 10px;
      -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      background: rgb(70, 77, 95);
    }
    .drawtree::-webkit-scrollbar-track {
      -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      border-radius: 0;
      background: rgba(0, 0, 0, 0.1);
    }
    .drawtools {
      padding-bottom: 20px;
    }

    .saved {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: #6570795e;

      .inner {
        position: absolute;
        left: 45%;
        top: 40%;
        background-image: url("/images/backg33.png");
        background-size: 100% 100%;
        color: #fff;
        height: 154px;
        width: 271px;
        text-align: center;

        .buttenrow {
          position: absolute;
          bottom: 24px;
          text-align: center;
          width: 100%;
        }

        .el-row {
          padding: 10px;

          input {
            width: 53%;
            margin-left: 15px;
          }
        }
      }
    }

    > .el-row {
      position: relative;
      left: 120px;
    }

    .file {
      width: 58px;
      height: 26px;
      line-height: 26px;
      padding: 0;
      border: 1px solid rgba(76, 109, 141, 1);
      background: rgba(3, 14, 21, 1);
      color: #577ba0;
    }
    .file:hover {
      color: #409eff;
    }
    .con {
      width: 90px;
    }

    .splitline {
      position: relative;
      width: 100%;
    }

    .choose {
      .title {
        padding: 0 0 20px;
      }

      .el-select {
        display: block;
        padding: 0 0 20px;

        .el-select-dropdown__item {
          color: #fff;
        }
      }

      .el-button {
        width: 60px;
        height: 30px;
        line-height: 30px;
        padding: 0;
      }
    }
    #pane-first {
      overflow: hidden;
      overflow-y: auto;
    }
    #pane-first::-webkit-scrollbar {
      width: 4px;
    }
    #pane-first::-webkit-scrollbar-thumb {
      border-radius: 10px;
      -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      background: rgb(70, 77, 95);
    }
    #pane-first::-webkit-scrollbar-track {
      -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      border-radius: 0;
      background: rgba(0, 0, 0, 0.1);
    }
    #pane-second {
      overflow: hidden;
      overflow-y: auto;
    }
    #pane-second::-webkit-scrollbar {
      width: 4px;
    }
    #pane-second::-webkit-scrollbar-thumb {
      border-radius: 10px;
      -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      background: rgb(70, 77, 95);
    }
    #pane-second::-webkit-scrollbar-track {
      -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
      border-radius: 0;
      background: rgba(0, 0, 0, 0.1);
    }
  }
}
</style>